import router from '@/router'
import { getRawRoute } from '@/utils/router-helper'
import { defineStore } from 'pinia'
import { store } from '../index'
import { findIndex } from '@/utils'
import { useUserStoreWithOut } from './user'

export const useTagsViewStore = defineStore('tagsView', {
  state: () => ({
    visitedViews: [],
    cachedViews: new Set(),
    selectedTag: undefined
  }),
  getters: {
    getVisitedViews() {
      return this.visitedViews
    },
    getCachedViews() {
      return Array.from(this.cachedViews)
    },
    getSelectedTag() {
      return this.selectedTag
    }
  },
  actions: {
    // 添加标签和缓存
    addView(view) {
      this.addVisitedView(view)
      this.addCachedView()
    },

    // 添加访问标签页
    addVisitedView(view) {
      if (this.visitedViews.some((v) => v.path === view.path)) return
      if (view.meta && view.meta.noTagsView) return

      this.visitedViews.push(
        Object.assign({}, view, {
          title: (view.meta && view.meta.title) || 'no-name'
        })
      )
    },

    // 添加缓存页
    addCachedView() {
      const cacheMap = new Set()
      for (const v of this.visitedViews) {
        const item = getRawRoute(v)
        const needCache = !(item.meta && item.meta.noCache)
        if (!needCache) continue
        if (item.name) {
          cacheMap.add(item.name)
        }
      }

      if (
        Array.from(this.cachedViews).sort().toString() ===
        Array.from(cacheMap).sort().toString()
      ) {
        return
      }

      this.cachedViews = cacheMap
    },

    // 删除某个标签和缓存
    delView(view) {
      this.delVisitedView(view)
      this.addCachedView()
    },

    // 删除访问标签
    delVisitedView(view) {
      for (let i = 0; i < this.visitedViews.length; i++) {
        if (this.visitedViews[i].path === view.path) {
          this.visitedViews.splice(i, 1)
          break
        }
      }
    },

    // 删除缓存
    delCachedView() {
      const route = router.currentRoute.value
      const index = findIndex(this.getCachedViews, (v) => v === route.name)
      if (index > -1) {
        this.cachedViews.delete(this.getCachedViews[index])
      }
    },

    // 删除全部标签和缓存
    delAllViews() {
      this.delAllVisitedViews()
      this.addCachedView()
    },

    // 删除所有标签（保留 affix 标签）
    delAllVisitedViews() {
      const userStore = useUserStoreWithOut()
      this.visitedViews = userStore.getUserInfo
        ? this.visitedViews.filter((tag) => tag.meta && tag.meta.affix)
        : []
    },

    // 删除其它标签和缓存
    delOthersViews(view) {
      this.delOthersVisitedViews(view)
      this.addCachedView()
    },

    // 删除其它标签
    delOthersVisitedViews(view) {
      this.visitedViews = this.visitedViews.filter((v) => {
        return (v.meta && v.meta.affix) || v.path === view.path
      })
    },

    // 删除左侧标签
    delLeftViews(view) {
      const index = findIndex(this.visitedViews, (v) => v.path === view.path)
      if (index > -1) {
        this.visitedViews = this.visitedViews.filter((v, i) => {
          return (v.meta && v.meta.affix) || v.path === view.path || i > index
        })
        this.addCachedView()
      }
    },

    // 删除右侧标签
    delRightViews(view) {
      const index = findIndex(this.visitedViews, (v) => v.path === view.path)
      if (index > -1) {
        this.visitedViews = this.visitedViews.filter((v, i) => {
          return (v.meta && v.meta.affix) || v.path === view.path || i < index
        })
        this.addCachedView()
      }
    },

    // 更新某个标签信息
    updateVisitedView(view) {
      for (let i = 0; i < this.visitedViews.length; i++) {
        if (this.visitedViews[i].path === view.path) {
          this.visitedViews[i] = Object.assign(this.visitedViews[i], view)
          break
        }
      }
    },

    // 设置当前选中标签
    setSelectedTag(tag) {
      this.selectedTag = tag
    },

    // 设置标题
    setTitle(title, path) {
      for (const v of this.visitedViews) {
        if (v.path === (path || (this.selectedTag && this.selectedTag.path))) {
          v.meta.title = title
          break
        }
      }
    }
  },
  persist: false
})

// 外部使用（setup 外部使用）
export const useTagsViewStoreWithOut = () => {
  return useTagsViewStore(store)
}
